﻿/*******************************************************
Copyright © 2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/

using System;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;

using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Controls;

using facebook.Schema;
using ATGi.CS.Facebook.Data;

namespace ATGi.CS.Facebook.Controls
{
    public class FacebookLoginForm : WrappedFormBase
    {
        FacebookLoginButton fbLoginButton;
        private UserInvitation invitation = null;

        public string FacebookLoginButtonId
        {
            get { return (string)ViewState["FacebookLoginButtonId"] ?? string.Empty; }
            set { ViewState["FacebookLoginButtonId"] = value; }
        }

        /// <summary>
        /// Gets or sets the success actions.
        /// </summary>
        /// <value>The success actions.</value>
        [
        Browsable(false),
        DefaultValue(null),
        Description("Defines the actions to take when the user is logged in successfully"),
        PersistenceMode(PersistenceMode.InnerProperty),
        ]
        public virtual Actions SuccessActions
        {
            get { return _successActions; }
            set
            {
                if (_successActions != null)
                    this.Controls.Remove(_successActions);

                _successActions = value;
                if (_successActions != null)
                    this.Controls.Add(_successActions);
            }
        }
        private Actions _successActions;

        /// <summary>
        /// Gets or sets the failure actions.
        /// </summary>
        /// <value>The failure actions.</value>
        [
        Browsable(false),
        DefaultValue(null),
        Description("Defines the actions to take when the user fails to login"),
        PersistenceMode(PersistenceMode.InnerProperty),
        ]
        public virtual Actions FailureActions
        {
            get { return _failureActions; }
            set
            {
                if (_failureActions != null)
                    this.Controls.Remove(_failureActions);

                _failureActions = value;
                if (_failureActions != null)
                    this.Controls.Add(_failureActions);
            }
        }
        private Actions _failureActions;

        protected override void AddPropertyControls()
        {
            if (this.SuccessActions != null)
                this.Controls.Add(this.SuccessActions);

            if (this.FailureActions != null)
                this.Controls.Add(this.FailureActions);

            base.AddPropertyControls();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            CSContext csContext = CSControlUtility.Instance().GetCurrentCSContext(this.Page);

            if (Page.Request.IsAuthenticated)
            {
                // user is already logged in
                if (csContext.RewrittenUrlName.StartsWith("login"))
                    throw new CSException(CSExceptionType.UserAlreadyLoggedIn, csContext.ReturnUrl);
                else
                {
                    this.AutomatedVisible = false;
                    return;
                }
            }

            CSControlUtility.Instance().EnsureSecureConnection(this.Context);

            if (csContext.SiteSettings.AccountActivation == AccountActivation.InvitationOnly && !Globals.IsNullorEmpty(csContext.Context.Request["InvitationKey"]))
            {
                Guid invitationKey = Guid.Empty;
                try
                {
                    invitationKey = new Guid(csContext.Context.Request["InvitationKey"]);
                }
                catch { }

                if (invitationKey != Guid.Empty)
                    invitation = UserInvitations.GetUserInvitation(invitationKey);
            }
        }

        protected override void AttachChildControls()
        {
            fbLoginButton = CSControlUtility.Instance().FindControl(this, FacebookLoginButtonId) as FacebookLoginButton;
            IFacebookUser fbUser = KernelContainer.Get<IFacebookUser>();
            if (OnFacebookLoginForm && fbUser.IsValid && CSContext.Current.User.IsAnonymous)
            {
                // The FB user is known and the CS user is not logged in.
                // TODO: (JJE) I would like to display the user info and a different button to login with the fb account.
                DoLogin(fbUser);
            }
        }

        private bool OnFacebookLoginForm
        {
            get
            {
                bool onFacebookLoginForm = false;
                string loginType = CSContext.Current.QueryString["Type"];
                if (!string.IsNullOrEmpty(loginType) && loginType.Equals("facebook", StringComparison.InvariantCultureIgnoreCase))
                    onFacebookLoginForm = true;
                return onFacebookLoginForm;
            }
        }



        private void DoLogin(IFacebookUser user)
        {
            User csUser = null;
            using (var dc = KernelContainer.Get<FBDataContext>())
            {
                var fbUser = dc.FacebookUsers.Where(u => u.FacebookID == user.ID).FirstOrDefault();
                if (fbUser != null)
                    csUser = Users.GetUser(fbUser.UserID, false);
            }
            if (csUser != null)
                ProcessLoginRequest(csUser);

            if (this.FailureActions != null)
                this.FailureActions.Execute(this, null);
        }  

        private void ProcessLoginRequest(User userToLogin)
        {
            CSContext csContext = CSControlUtility.Instance().GetCurrentCSContext(this.Page);

            // Are we allowing login?
            if (!csContext.SiteSettings.AllowLogin && !userToLogin.IsAdministrator)
            {
                throw new CSException(CSExceptionType.UserLoginDisabled);
            }

            HttpCookie formsAuthCookie = FormsAuthentication.GetAuthCookie(userToLogin.Username, true);

            UserCookie userCookie = csContext.User.GetUserCookie();
            userCookie.WriteCookie(formsAuthCookie, 30, true);

            // if we're logging in with an invitation, accept the invitation
            if (invitation != null)
                UserInvitations.Accept(invitation, csContext.User);

            if (this.SuccessActions != null)
                this.SuccessActions.Execute(this, userToLogin);
        }

    }
}
